//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.WindowsPhoneChat.Commands
{
    using System;
    using Microsoft.Samples.AccessControl;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.Controllers;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.ViewModels;

    public class LoginCommand : AsyncCommand<LoginControlViewModel>
    {
        protected override bool CanExecute(LoginControlViewModel viewModel)
        {
            return viewModel != null;
        }

        protected override void Execute(LoginControlViewModel viewModel)
        {
            if (viewModel == null)
            {
                return;
            }

            // Login might take a little while - update the UI to show an indeterminate progress bar
            viewModel.State = "LoggingIn";

            // Asynchronously begin a request to get an auth token from ACS - call LoginCompleted 
            // when the request completes
            App.Context.TokenProvider.BeginGetToken(false, this.OnLoginCompleted, viewModel);
        }

        private void OnLoginCompleted(IAsyncResult result)
        {
            SimpleWebToken token;
            var viewModel = (LoginControlViewModel)result.AsyncState;

            try
            {
                // End the async request - if it failed, an exception will be thrown here
                token = App.Context.TokenProvider.EndGetToken(result);

                //// Update the UI and navigate to the main page
                ViewController.Current.BeginInvokeUI(() =>
                {
                    // Initialize the App: this initializes a messaging factory and namespace client
                    // and also begins a timer to renew this token a few minutes before it expires.
                    App.Context.CompleteAuthentication(viewModel.UserName);

                    this.OnExecuteCompleted(viewModel);
                });
            }
            catch (Exception e)
            {
                App.ShowError(e);
                this.OnExecuteCompleted(viewModel, true);
            }
        }
    }
}
